package com.movil.art;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import utils.ParcheInputStream;
import utils.ProductosCat;
import utils.Valores;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ProductosListCatLV extends ListActivity{

	private ArrayList<ProductosCat> listaProductos = null;
	private static final String HOST = Valores.HOST; //esto es para el equipo local
	private static final String SOAP_ACTION = "capeconnect:servicios:serviciosPortType#obtenerProductosPorCategoria";
    private static final String METHOD_NAME = "obtenerProductosPorCategorias";
    private static final String NAMESPACE = "http://www.your-company.com/servicios.wsdl";
    private static final String URL = "http://"+HOST+"/servicios/servicios.php";
    private SoapSerializationEnvelope envelope; 
    private HttpTransportSE httpt;
    private Bundle bundleResult=new Bundle();
    private Bundle bundle = null;
    private String resultData;
    
    private SoapObject result;
    private IconListViewAdapter adaptador;
    
    //botones
    private ImageView ivCesta = null;
    private ImageView ivRegresa = null;
    private ImageView ivInicio = null;
	
    private final static int IO_BUFFER_SIZE = 4 * 1024;
	
	public void onCreate(Bundle savedInstanceState) {
		try{
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.productoslistcatlv);
	        
	        //acciones
	        ivRegresa = (ImageView)findViewById(R.id.ivRegresarProListCatLV);
	        ivRegresa.setOnClickListener(ivRegresaPres);
	        ivInicio = (ImageView) findViewById(R.id.ivInicioProdListCatLV);
	        ivInicio.setOnClickListener(ivInicioPres);
	        
	        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
	
	        httpt = new HttpTransportSE(URL);
	        envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
	        envelope.dotNet = false;
	        
	        bundle = getIntent().getExtras();
	        /*
	        TextView nombreCat = (TextView) findViewById(R.id.tvCatNombCategoria);
	        nombreCat.setText(bundle.getString("nombreCat"));
	        */ 
	        request.addProperty ("idCategoria", bundle.getString("idCategoria"));
	        envelope.setOutputSoapObject(request);
	        inicializaProd();
	        this.adaptador = new IconListViewAdapter(this, R.layout.productoslistcatlvrow, listaProductos);
	        setListAdapter(this.adaptador);
	        
	        ivCesta = (ImageView)findViewById(R.id.ivCestaListCatLV);
	        ivCesta.setOnClickListener(ivCestaPres);
	        

		}
		catch (Exception e) {
	    	new AlertDialog.Builder(ProductosListCatLV.this)

	    	.setTitle("error en valores()")

	    	.setMessage(e.toString())

	    	.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

	    	public void onClick(DialogInterface dialog, int whichButton) {

	    	setResult(RESULT_OK);
	    	  }
	    	})
	    	.show();
	    }
        
    }
	
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
    	return super.onKeyDown(keyCode, event);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        ProductosCat producto = (ProductosCat) l.getItemAtPosition(position);        
        //Toast.makeText(this, producto.getNombreProd(), Toast.LENGTH_LONG).show();
        if (producto.getIdProd() != null){
			Intent i = new Intent(); 
			i.putExtra("idProducto",producto.getIdProd());
			i.putExtra("idCategoria", bundle.getString("idCategoria"));
			i.setClass(ProductosListCatLV.this, DescripcionProdSelec.class);
			startActivity(i);     
			finish();
        }
    }
	/*
    public Bundle valores(String cadena){
    	String value;
    	try{
        if (resultData.startsWith("anyType")) { // if JSON string is an object 
     	    JSONObj = new JSONObject(cadena); 
     	    Iterator<String> itr = JSONObj.keys(); 
     	    while (itr.hasNext()) { 
     	        String Key = (String) itr.next(); 
     	        value = JSONObj.getString(Key); 
     	        bundleResult.putString(Key, value);
     	         Log.i(Key,bundleResult.getString(Key)); 
     	    }
         }
    } catch (Exception e) {
    	new AlertDialog.Builder(ProductosListCatLV.this)

    	.setTitle("error en valores()")

    	.setMessage(e.toString())

    	.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

    	public void onClick(DialogInterface dialog, int whichButton) {

    	setResult(RESULT_OK);
    	  }
    	})
    	.show();
    }
        return bundleResult;
    }
*/
	
	private void inicializaProd(){
	   listaProductos = new ArrayList<ProductosCat>();
       try{
	       httpt.call(SOAP_ACTION, envelope);
	       result = (SoapObject)envelope.bodyIn;
	       
	       SoapObject result2 =  (SoapObject) envelope.getResponse();
	      
		   SoapObject prod = (SoapObject) result2.getProperty("productos");
		   if (prod.getPropertyCount()!=0){
		       for(int cont=0; cont< result2.getPropertyCount(); cont ++){
		    	 SoapObject resultados = (SoapObject) result2.getProperty(cont);
		    	 SoapPrimitive id = (SoapPrimitive) resultados.getProperty("idProd");
	          	 SoapPrimitive nombre = (SoapPrimitive) resultados.getProperty("nombreProd");
	          	 SoapPrimitive imagen = (SoapPrimitive) resultados.getProperty("imagenProd");
	          	 SoapPrimitive precio = (SoapPrimitive) resultados.getProperty("precioProd");
	          	 SoapPrimitive fabricante = (SoapPrimitive) resultados.getProperty("fabricanteProd");
		    	 
	          	 double precioF = Double.parseDouble(precio.toString());
		      	 
		      	 ProductosCat productosCat = new ProductosCat();
		      	 productosCat.setIdProd(id.toString());
		      	 productosCat.setNombreProd(nombre.toString());
		      	 productosCat.setImagenProd(imagen.toString());
		      	 productosCat.setPrecioProd(Double.toString(precioF));
		      	 productosCat.setNombreFabricante(fabricante.toString());
		      	 listaProductos.add(productosCat);
		       }
		   }
		   else{
		      	 ProductosCat productosCat = new ProductosCat();
		      	 productosCat.setIdProd(null);
		      	 productosCat.setNombreProd(null);
		      	 productosCat.setImagenProd(null);
		      	 productosCat.setPrecioProd(null);
		      	 productosCat.setNombreFabricante(null);
		      	 listaProductos.add(productosCat);			   
		   }
			   
       }
   	catch(Exception err){
    	new AlertDialog.Builder(ProductosListCatLV.this)

    	.setTitle("error en inicializaCat()")

    	.setMessage(err.toString())

    	.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

    	public void onClick(DialogInterface dialog, int whichButton) {

    	setResult(RESULT_OK);
    	  }
    	})
    	.show();   		
	}


	}
	
	 public class IconListViewAdapter extends ArrayAdapter<ProductosCat> {

	        private ArrayList<ProductosCat> items;
	        private String url = "http://"+HOST+"/catalog/images/";

	        public IconListViewAdapter(Context context, int textViewResourceId, ArrayList<ProductosCat> items) {
	                super(context, textViewResourceId, items);
	                this.items = items;
	        }
	        @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
	                View v = convertView;
	                if (v == null) {
	                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                    v = vi.inflate(R.layout.productoslistcatlvrow, null);
	                }
	                ProductosCat productosCat = items.get(position);
	                if (productosCat != null) {
	                	
	                	//poblamos la lista de elementos
	                	
	                        TextView nombreProd = (TextView) v.findViewById(R.id.tvNombreProdLv);
	                        ImageView imagenProd = (ImageView) v.findViewById(R.id.ivImagenProdLv);
	                        TextView precioProd = (TextView) v.findViewById(R.id.tvPrecioProdLv);
	                        //TextView fabricanteProd = (TextView) v.findViewById(R.id.tv);
	                        
	            			try{
	            				ImageView i = new ImageView(ProductosListCatLV.this);
	            				
	            				/*
	            				String rutaUrl = url+productosCat.getImagenProd();
	            				BitmapFactory.Options options=new BitmapFactory.Options();
	            				options.inSampleSize = 1;
	
	            				URL aURL = new URL(url+productosCat.getImagenProd()); 
	            	            URLConnection conn = aURL.openConnection(); 
	            	            conn.connect();
	            	            InputStream is = conn.getInputStream();                  
	            	            BufferedInputStream bis = new BufferedInputStream(is); 
	            	            Bitmap bm = BitmapFactory.decodeStream(bis,null, options); 
	            	            bis.close(); 
	            	            is.close();
	            	            
	            				if (bm == null){
	            					Log.e("Erro bitmap", "error");
	            				}
	            				Bitmap bMapEScala = Bitmap.createScaledBitmap(bm, 80, 80, true);
	            				if (bMapEScala == null){
	            					Log.e("Erro bitmap Escala", "error");
	            				}	            				
	            				*/
	            				/*
	            				URL aURL = new URL(url+productosCat.getImagenProd()); 
	            	            URLConnection conn = aURL.openConnection(); 
	            	            conn.connect();
	            	            InputStream is = conn.getInputStream();                  
	            	            BufferedInputStream bis = new BufferedInputStream(is); 
	            	            Bitmap bm = BitmapFactory.decodeStream(bis); 
	            	            bis.close(); 
	            	            is.close();
	            	            */
	            				
	        		        	//cambio
	            				
	                        	String rutaUrl = url+productosCat.getImagenProd();
	            				HttpGet httpRequest = null;
	            				try {
	            					httpRequest = new HttpGet(rutaUrl);
	            				} catch (Exception e) {
	            					e.printStackTrace();
	            				}
	            				
	            				BitmapFactory.Options bfOpt = new BitmapFactory.Options();
	            				BufferedOutputStream bos = null;

	            		        bfOpt.inScaled = true;
	            		        bfOpt.inSampleSize = 1;
	            		        bfOpt.inPurgeable = true;
	            		        
	            				
	            				HttpClient httpclient = new DefaultHttpClient();
	            		        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
	            		        HttpEntity entity = response.getEntity();
	            		        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
	            		        InputStream instream = bufHttpEntity.getContent();
	            		        //Bitmap bm = BitmapFactory.decodeStream(instream,null,bfOpt);
	            		        Bitmap bm = BitmapFactory.decodeStream(new ParcheInputStream(instream),null,bfOpt);
	            		        Bitmap bMapEScala;
	            		        if (bm == null){
	            		        	Log.e("error", "Error en BitMap");
	            		        	Resources res = getResources();
	            		        	Drawable drawable = res.getDrawable(R.drawable.categorias64x64);
	            		        	i.setImageDrawable(drawable);
	            		        	Bitmap bmp=((BitmapDrawable)drawable).getBitmap();
	            		        	bMapEScala = Bitmap.createScaledBitmap(bmp, 64,64, true);
	            		        }
	            		        else{
	            		        	bMapEScala = Bitmap.createScaledBitmap(bm, 80, 80, true);	
	            		        }

	            		       
	            		        
	            				//fin

	            	            //nuevo
	            				/*
	            				Bitmap bm = null;

	            			    InputStream in = null;

	            			    BufferedOutputStream out = null;
	            			    
	            			    

	            			    try {

	            			            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);



	            			            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();

	            			            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);

	            			            copy(in, out);

	            			            out.flush();



	            			            final byte[] data = dataStream.toByteArray();

	            			            bm = BitmapFactory.decodeByteArray(data, 0, data.length);





	            			   } catch (Exception err){
	            				   	Log.e("Error", err.toString());

	            			   }    
	            			   Bitmap bMapEScala = Bitmap.createScaledBitmap(bm, 80, 80, true);
	            			   */
	            				//fin
	            				
	            				
	            		        if (bm != null){
	            		        	i.setImageBitmap(bMapEScala);	
		            		    }
	            	            
	            	            //i.setScaleType(ImageView.ScaleType.FIT_CENTER); 
	            	            i.setLayoutParams(new GridView.LayoutParams(80, 80));
	            	            
		            			if (imagenProd != null){
			            			   imagenProd.setImageBitmap(bMapEScala);
			            		}
		            			//instream.close();

	            			}
	            			catch(Exception err)
	            			{
	            				Log.e("Error grid" , err.toString());
	            			}
	            			if (nombreProd != null){
	            			   nombreProd.setText(productosCat.getNombreProd());
	            			}
	            			if (precioProd != null){
		            			   precioProd.setText(productosCat.getPrecioProd());
		            			}
	            			
	                        /*
	                        if (im!= null) {
	                        	im.setImageResource(o.getLocalImage());
	                        }                        
	                        if (tt != null) {             
	                            tt.setText(o.getLocalName());                             
	                        } 
	                        */   	                    	                        
	                }
	                return v;
	        }
	}
	 
	    
	 
	 private OnClickListener ivCestaPres = new OnClickListener() {
		
		public void onClick(View arg0) {
			Intent i = new Intent(); 
			i.setClass(ProductosListCatLV.this, Cesta.class);
			startActivity(i);	
			finish();
		}
	};

	private OnClickListener ivRegresaPres = new OnClickListener() {
		
		public void onClick(View v) {
           Intent intent = new Intent();
           intent.putExtra("idCategoria", bundle.getString("idCategoria"));
           intent.setClass(ProductosListCatLV.this, MuestraCategorias.class);
           startActivity(intent);
           finish();		   
		}
	};
	
	private OnClickListener ivInicioPres = new OnClickListener() {
		
		public void onClick(View arg0) {
           Intent intent = new Intent();
           intent.setClass(ProductosListCatLV.this, Principal.class);
           startActivity(intent);
           finish();		
		}
	};
	
}
